package org.example.service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.domain.ProdTagReference;
import org.example.domain.Sku;
import org.example.mapper.ProdTagReferenceMapper;
import org.example.mapper.SkuMapper;
import org.example.model.ChangeStock;
import org.example.model.ProdChange;
import org.example.model.SkuChange;
import org.example.service.ProdTagReferenceService;
import org.example.service.SkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.domain.Prod;
import org.example.mapper.ProdMapper;
import org.example.service.ProdService;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ProdServiceImpl extends ServiceImpl<ProdMapper, Prod> implements ProdService{

    @Autowired
    private ProdMapper prodMapper;

    @Autowired
    private ProdTagReferenceService prodTagReferenceService;

    @Autowired
    private SkuService skuService;

    @Autowired
    private ProdTagReferenceMapper prodTagReferenceMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveProd(Prod prod) {
        prod.setShopId(1L);
        prod.setSoldNum(0);
        prod.setCreateTime(new Date());
        prod.setUpdateTime(new Date());
        prod.setPutawayTime(new Date());
        prod.setVersion(0);
        Prod.DeliveryModeVo deliveryModeVo = prod.getDeliveryModeVo();
        prod.setDeliveryMode(JSONObject.toJSONString(deliveryModeVo));

        int i = prodMapper.insert(prod);

        if (i > 0) {
           //处理商品和分组标签的关系
           Long prodId = prod.getProdId();
           List<Long> tagIdList = prod.getTagList();
           if (CollectionUtil.isNotEmpty(tagIdList) && tagIdList.size() != 0){
               List<ProdTagReference> prodTagReferencesList = new ArrayList<>();
               tagIdList.forEach(tagId -> {
                   ProdTagReference prodTagReference = new ProdTagReference();
                   prodTagReference.setTagId(tagId);
                   prodTagReference.setProdId(prodId);
                   prodTagReference.setCreateTime(new Date());
                   prodTagReference.setShopId(1L);
                   prodTagReference.setStatus(1);
                   prodTagReferencesList.add(prodTagReference);
               });
               prodTagReferenceService.saveBatch(prodTagReferencesList);
           }
           //处理商品和sku的关系
           List<Sku> skuList = prod.getSkuList();
           if (CollectionUtil.isNotEmpty(skuList) && skuList.size() != 0){
               skuList.forEach(sku -> {
                   sku.setProdId(prodId);
                   sku.setCreateTime(new Date());
                   sku.setUpdateTime(new Date());
                   sku.setVersion(0);
                   sku.setActualStocks(sku.getStocks());
               });
               skuService.saveBatch(skuList);
           }
        }

        return i>0;
    }

    @Override
    public Prod queryProdInfoById(Long prodId) {
        //根据商品标识查询商品详情
        Prod prod = prodMapper.selectById(prodId);
        if (ObjectUtil.isNull(prod)) {
            return prod;
        }
        //根据商品标识查询商品与分组标签的关系
        List<ProdTagReference> prodTagReferenceList = prodTagReferenceMapper.selectList(new LambdaQueryWrapper<ProdTagReference>()
                .eq(ProdTagReference::getProdId, prodId)
        );
        //判断是否有值
        if (CollectionUtil.isNotEmpty(prodTagReferenceList) && prodTagReferenceList.size() != 0) {
            //从商品与分组标签的关系集合中获取分组标签id集合
            List<Long> tagIdList = prodTagReferenceList.stream().map(ProdTagReference::getTagId).collect(Collectors.toList());
            prod.setTagList(tagIdList);
        }
        //根据商品id查询商品Sku对象集合
        List<Sku> skus = skuMapper.selectList(new LambdaQueryWrapper<Sku>()
                .eq(Sku::getProdId, prodId)
        );
        prod.setSkuList(skus);
        return prod;
    }

    @Override
    public Boolean modifyProdInfo(Prod prod) {
        Long prodId = prod.getProdId();
        //删除商品与分组标签的关系
        prodTagReferenceMapper.delete(new LambdaQueryWrapper<ProdTagReference>()
                .eq(ProdTagReference::getProdId, prodId));
        //处理商品与分组标签的关系
        List<Long> tagIdList = prod.getTagList();
        if (CollectionUtil.isNotEmpty(tagIdList) && tagIdList.size() != 0){
            List<ProdTagReference> prodTagReferencesList = new ArrayList<>();
            tagIdList.forEach(tagId -> {
                ProdTagReference prodTagReference = new ProdTagReference();
                prodTagReference.setTagId(tagId);
                prodTagReference.setProdId(prodId);
                prodTagReference.setCreateTime(new Date());
                prodTagReference.setShopId(1L);
                prodTagReference.setStatus(1);
                prodTagReferencesList.add(prodTagReference);
            });
            prodTagReferenceService.saveBatch(prodTagReferencesList);
        }
        //批量修改商品与sku的关系
        List<Sku> skuList = prod.getSkuList();
        skuList.forEach(sku -> {
            sku.setUpdateTime(new Date());
            sku.setActualStocks(sku.getStocks());
        });

        List<Sku> dbSkuList = skuMapper.selectList(new LambdaQueryWrapper<Sku>().eq(Sku::getProdId, prodId));
        if (CollectionUtil.isNotEmpty(dbSkuList) && dbSkuList.size() != 0 && dbSkuList.size() < skuList.size()){
            //删除数据库中的数据，插入新的数据
            skuMapper.delete(new LambdaQueryWrapper<Sku>().eq(Sku::getProdId, prodId));
            skuList.forEach(sku -> {
                sku.setProdId(prodId);
                sku.setCreateTime(new Date());
                sku.setUpdateTime(new Date());
                sku.setVersion(0);
                sku.setActualStocks(sku.getStocks());
            });
            skuService.saveBatch(skuList);
        }
        skuService.updateBatchById(skuList);

        prod.setUpdateTime(new Date());
        return prodMapper.updateById(prod) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeProdById(Long prodId) {
        // 删除商品与分组标签的关系
        prodTagReferenceMapper.delete( new LambdaQueryWrapper<ProdTagReference>()
                .eq(ProdTagReference::getProdId, prodId)
    );
        // 根据商品id删除商品sku对象
        skuMapper.delete( new LambdaQueryWrapper<Sku>()
                .eq(Sku::getProdId, prodId)
    );
        return prodMapper.deleteById( prodId) > 0;
    }

    @Override
    public Prod queryWxProdInfoByProdId(Long prodId) {

        // 根据标识查询商品信息
        Prod prod = prodMapper.selectById( prodId);
        // 根据商品标识查询商品sku对象
        List<Sku> skus = skuMapper.selectList(new LambdaQueryWrapper<Sku>()
                .eq(Sku::getProdId, prodId)
        );
        prod.setSkuList(skus);
        return prod;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean changeProdAndSkuChangeStock(ChangeStock changeStock) {
        Boolean flag = false;
        // 获取商品sku购买数量对象
        List<SkuChange> skuChangeList = changeStock.getSkuChangeList();
        for (SkuChange skuChange : skuChangeList) {
            Long skuId = skuChange.getSkuId();
            Sku sku = skuMapper.selectById( skuId);
            Integer count = skuMapper.updateSkuStock(skuId, skuChange.getCount(), sku.getVersion());
            if (count == 1) {
                flag = true;
            } else {
                throw new RuntimeException("更新失败");
            }
        }

        // 获取商品prod购买数量对象
        List<ProdChange> prodChangeList = changeStock.getProdChangeList();
        for (ProdChange prodChange : prodChangeList) {
            Long prodId = prodChange.getProdId();
            Prod prod = prodMapper.selectById( prodId);
            Integer count = prodMapper.updateProdStock(prodId, prodChange.getCount(), prod.getVersion());
            if (count == 1) {
                flag = true;
            } else {
                throw new RuntimeException("更新失败");
            }
        }
        return flag;
    }

    @Override
    public Prod queryWxSeckillProdInfoByProdId(Long prodId,Long skuId) {

        // 根据标识查询商品信息
        Prod prod = prodMapper.selectById( prodId);
        // 根据商品标识查询商品sku对象
        List<Sku> skus = skuMapper.selectList(new LambdaQueryWrapper<Sku>()
                .eq(Sku::getProdId, prodId)
                .eq(Sku::getSkuId, skuId)
        );
        prod.setSkuList(skus);
        return prod;
    }
}
